/*
* author:danny
* desc:
* date:
* */




import {Actions} from "react-native-router-flux"

import * as URL from '../api/URL';
import * as CACHE from '../tools/cache'

//打包url
function urlPackage(payload) {
    let url = URL.domain + payload.url;

    _.forIn(payload.getPara, function(value, key) {
        url+= key+"="+value+"&"
    });
    if(url.charAt(url.length-1) === "&"){
        url = url.substr(0,url.length-1)
    }

    if(url.charAt(url.length-1) === "?"){
        url = url.substr(0,url.length-1)
    }

    return url;
}

//url 请求
function fetchData(payload){
    let url = urlPackage(payload);

    //http 请求信息
    let opts  = {
        method:payload.method || "GET"  ,
        headers:{
            "Accept": "application/json",
            "Content-Type": 'application/json',
        },
        body:payload.method === 'POST'?JSON.stringify(payload.postData):null
    };


    return new Promise(function (resolve, reject) {
        fetch(url,opts )
            .then((response)=>{
                //检查是否请求成功
                if (response.status === 200 ) {
                    return response.json();
                }
                //抛出错误
                const error = new Error(response.statusText);
                error.response = response;
                throw error;
            }).then(responeData=>{
                resolve (responeData);
            }).catch(error=>{
                reject(error);
        })
    })
}

const  http =  (store) =>  (next) => async  (action) =>{
    //不需要网络请求的
    if(!action.payload){
        return next(action);
    }

    //缓存接口数据，减少访问后台次数
    if(action.expired){
        let cacheResult = await CACHE.getItem(urlPackage(action.payload));

        if(cacheResult){
            cacheResult = JSON.parse(cacheResult);
            let newTime = new Date().getTime();
            console.log("time ===>",cacheResult.saveIn + cacheResult.expired,newTime)
            if(cacheResult.saveIn + cacheResult.expired > newTime){
                action.result = cacheResult.data ;
                console.log("缓存数据 ===> ",cacheResult);
                return next(action);
            }


        }
    }
    //加载gif
    if(action.loading){
        Actions.loading();
    }
    console.log("发起网络请求 =====>",action.payload.url);
    //发起网络请求
    return fetchData(action.payload).then((respone)=>{
        //请求结束 关闭gif
        if(action.loading){
            Actions.pop();
        }

        //请求成功附加action
        if(action.success){
            _.forEach(action.success, (value,key)=> {
                store.dispatch(value);
            })
        }
        //获取到数据添加到action.result中,最后传到reducer
        action.result = respone;

        if(action.expired){
            CACHE.setItem(urlPackage(action.payload),JSON.stringify({
                data:action.result,
                expired:action.expired,
                saveIn:new Date().getTime()
            }))
        }
        //进入下个中间件
        return next(action);
    }).catch((error)=>{
        console.log("http error ==> ",error);
        //请求结束 关闭gif
        if(action.loading){
            Actions.pop();
        }
    })


};

export default http;
